package com.dongdongqiang.daogenerator.statement;

import com.dongdongqiang.daogenerator.pojo.TableColumn;
import com.dongdongqiang.daogenerator.pojo.TableMeta;
import com.dongdongqiang.daogenerator.utils.POJOUtils;

import java.lang.reflect.InvocationTargetException;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

/**
 * Created by ZZB on 2017/10/19.
 */
public class InsertPrepareStatementSetter implements IInsertPrepareStatementSetter {
    @Override
    public void setInPrepareStatement(PreparedStatement preparedStatement, TableMeta tableMeta, Object object) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException, NoSuchFieldException, SQLException {
        for (int i = 0; i < tableMeta.getTableColumns().size(); i++) {
            TableColumn tableColumn = tableMeta.getTableColumns().get(i);
            Object fieldResult = POJOUtils.readDeclaredFieldByGetMethod(object, tableColumn.getPropertyName());
            if(tableColumn.getPropertyType().equals(Date.class)){
                Instant instant = ((Date)fieldResult).toInstant();
                ZoneId zone = ZoneId.systemDefault();
                LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
                preparedStatement.setObject(i+1,localDateTime);
            } else {
                preparedStatement.setObject(i+1,fieldResult);
            }
        }
    }

    @Override
    public void setBatchInPrepareStatement(PreparedStatement preparedStatement, TableMeta tableMeta, List<?> objects) throws SQLException, NoSuchMethodException, NoSuchFieldException, IllegalAccessException, InvocationTargetException {
        for (Object object : objects) {
            setInPrepareStatement(preparedStatement, tableMeta, object);
            preparedStatement.addBatch();
        }
    }
}
